//
//  WNAdvertVC.swift
//  WalkNovel
//
//  Created by Kevin on 2023/7/4.
//

import UIKit

class WNAdvertVC: WNBaseVC {
    
    deinit {
        if advertTimer != nil {
            advertTimer?.invalidate()
            advertTimer = nil
        }
    }
    
    lazy var loadingView: UIImageView = {
        let image = UIImageView(image: UIImage(named: "logo_bg"))
        image.frame = view.bounds
        image.contentMode = .scaleAspectFill
        image.isUserInteractionEnabled = true
        let tapGesture = UITapGestureRecognizer.init(target: self, action: #selector(didTap))
        tapGesture.numberOfTapsRequired = 1
        image.addGestureRecognizer(tapGesture)
        return image
    }()
    
    lazy var timeBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitleColor(.white, for: .normal)
        btn.titleLabel?.font = .wn_font(name: .bold, size: 15)
        btn.backgroundColor = .init(named: "red_FE95B4")
        btn.rx.tap.bind { [weak self] in
            self?.goToMainVC()
        }.disposed(by: rx.disposeBag)
        btn.wn_cornerWithBorder(4)
        return btn
    }()
    
    var advertTimer: Timer?
    
    var seconds: Int = 5
    
    var adModel: ADModel? {
        didSet {
            if let m = adModel {
                loadingView.wn_setupImg(m.coverUrl, placeHolder: "logo_bg")
            }
        }
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        WNBuriedManager.shared.startEvents("ad page")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    override func viewConfig() {
        wn_hidNavView()
        view.addSubview(loadingView)
        view.addSubview(timeBtn)
        timeBtn.snp.makeConstraints { (make) in
            make.top.equalTo(StatusBarHeight)
            make.right.equalTo(-22)
            make.size.equalTo(CGSize(width: 82, height: 32))
        }
    }
    
    override func dataConfig() {
        adModel = ADModel.deserialize(from: getAdJson())
        seconds = adModel?.bookId == nil ? 0 : 4
        timeBtn.isHidden = adModel?.bookId == nil
        if getIsDeeplink() || seconds == 0 {
            goToMainVC()
        }else {
            advertTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
            RunLoop.current.add(advertTimer!, forMode: .common)
        }
    }
    
    @objc func updateTimer() {
        seconds -= 1
        timeBtn.setTitle("\(seconds)秒后跳過", for: .normal)
        if seconds <= 0 {
            goToMainVC()
        }
    }

    func cancelTimer() {
        if advertTimer != nil {
            advertTimer?.invalidate()
            advertTimer = nil
        }
    }
    
    @objc func goToMainVC() {
        saveAdJson([:])
        cancelTimer()
        changeMainRoot()
    }
    
    @objc func didTap() {
        saveTapAD(true)
        cancelTimer()
        changeMainRoot()
    }
}
